import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@WebServlet("/message/list2")
public class MessageListServletV2 extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Message> list=new ArrayList<>();
        //1.获取连接
        Connection connection= DBUtils.getConnection();
        //2.拼接sql，创建执行器
        String sql="select * from messages";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet=statement.executeQuery();
        while(resultSet.next()){
            String from=resultSet.getString("from");
            String to=resultSet.getString("to");
            String msg=resultSet.getString("message");
            list.add(new Message(from,to,msg));
        }
        DBUtils.close(resultSet,statement,connection);
        resp.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper=new ObjectMapper();
        resp.getWriter().write(objectMapper.writeValueAsString(list));
    }
}
